import axios from 'axios'
import Vue from "vue";
axios.defaults.timeout = 60000 // 设置请求时间
axios.defaults.baseURL = process.env.VUE_APP_BASEURL// 设置默认接口地址
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
// 路由请求拦截
axios.interceptors.request.use((config) => {
    config.headers.token = GetRequestParams().token||'';
    return config
}, (error) => {
    return Promise.reject(error)
})
var token401 = false;
// 路由响应拦截
axios.interceptors.response.use( response => {
    if (response.data.code == "401") {
        if(!token401){
            token401 = true;
            Vue.prototype.$alert('请重新登录或刷新页面', '会话已失效');
        }
    } 
    return response;
},error => {
    let msg= '服务器发生异常，请稍后再试';
    if(error.response){
        switch (error.response.status) {
            case 401:  msg= '会话已失效，请重新登录或刷新页面'; break;
            case 403:  msg= '您没有此操作权限访问'; break;
            case 503:  msg= '服务正在升级，请稍后再试'; break;
            case 504:  msg= '网关超时，请稍后再试'; break;
            default :  msg= '服务器发生异常，请稍后再试';    
        }  
    }
    Vue.prototype.$message.error(msg);
    return Promise.reject(error.response) // 返回接口返回的错误信息
});


export const GetRequestParams = () => {
    let url = location.search // 获取url中"?"符后的字串
    let theRequest = new Object()
    if (url.indexOf('?') != -1) {
        let str = url.substr(1)
        let strs = str.split('&')
        for (let i = 0; i < strs.length; i++) {
            theRequest[strs[i].split('=')[0]] = decodeURI(strs[i].split('=')[1])
        }
    }
    return theRequest
}

export function fetch (url, params = {}) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params: params
        })
        .then(response => {
            resolve(response.data)
        })
        .catch(err => {
            reject(err)
        })
    })
}

export function post (url, data = {}, config = {}) {
    return new Promise((resolve, reject) => {
        axios.post(url, data, config)
        .then(response => {
            resolve(response.data)
        }, err => {
            reject(err)
        })
    })
}
